import { useEffect, useState } from 'react';
import { Card, Row, Col, Statistic } from 'antd';
import { CheckCircleOutlined, ClockCircleOutlined } from '@ant-design/icons';
import ReactECharts from 'echarts-for-react';
import { todoAPI } from '../services/api';
import { Todo } from '../types';

const Dashboard = () => {
  const [todos, setTodos] = useState<Todo[]>([]);
  
  useEffect(() => {
    fetchTodos();
  }, []);

  const fetchTodos = async () => {
    try {
      const response = await todoAPI.getList();
      setTodos(response.data);
    } catch (error) {
      console.error('获取待办事项失败:', error);
    }
  };

  // 计算统计数据
  const completedTodos = todos.filter(todo => todo.status === 1);
  const completionRate = todos.length > 0 
    ? ((completedTodos.length / todos.length) * 100).toFixed(1) 
    : '0';

  // 按分类统计数据
  const getCategoryData = () => {
    const categoryMap = new Map<string, number>();
    todos.forEach(todo => {
      const count = categoryMap.get(todo.category) || 0;
      categoryMap.set(todo.category, count + 1);
    });
    return Array.from(categoryMap).map(([name, value]) => ({ name, value }));
  };

  // 获取近7天的完成率趋势
  const getTrendData = () => {
    const dates = Array.from({ length: 7 }, (_, i) => {
      const date = new Date();
      date.setDate(date.getDate() - i);
      return date.toISOString().split('T')[0];
    }).reverse();

    const dailyStats = dates.map(date => {
      const dayTodos = todos.filter(todo => 
        todo.created_at.split('T')[0] === date
      );
      const completed = dayTodos.filter(todo => todo.status === 1).length;
      const rate = dayTodos.length > 0 
        ? (completed / dayTodos.length) * 100 
        : 0;
      return [date, rate];
    });

    return dailyStats;
  };

  // 饼图配置
  const pieOption = {
    title: {
      text: '待办事项分类占比',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [{
      type: 'pie',
      radius: '50%',
      data: getCategoryData(),
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  };

  // 折线图配置
  const lineOption = {
    title: {
      text: '近7天完成率趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: getTrendData().map(item => item[0]),
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value}%'
      },
      max: 100
    },
    series: [{
      data: getTrendData().map(item => item[1]),
      type: 'line',
      smooth: true,
      areaStyle: {
        opacity: 0.3
      }
    }]
  };

  return (
    <div>
      <Row gutter={[16, 16]}>
        <Col xs={24} sm={12}>
          <Card>
            <Statistic
              title="总待办数"
              value={todos.length}
              prefix={<ClockCircleOutlined />}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12}>
          <Card>
            <Statistic
              title="完成率"
              value={completionRate}
              suffix="%"
              prefix={<CheckCircleOutlined />}
              precision={1}
            />
          </Card>
        </Col>
      </Row>

      <Row gutter={[16, 16]} style={{ marginTop: '16px' }}>
        <Col xs={24} lg={12}>
          <Card>
            <ReactECharts 
              option={pieOption} 
              style={{ height: '400px' }}
            />
          </Card>
        </Col>
        <Col xs={24} lg={12}>
          <Card>
            <ReactECharts 
              option={lineOption} 
              style={{ height: '400px' }}
            />
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default Dashboard; 